import React, { useState } from "react";
import { useSelector, useDispatch } from "react-redux";
import { SwitchState, delPer, addPer, EditPer } from "../../store/PersonSlice";
import { useNavigate } from "react-router-dom";
import {
  NavBar,
  NoticeBar,
  Button,
  Card,
  List,
  Checkbox,
  Modal,
  Form,
  Input,
  Toast,
} from "antd-mobile";
import { EditSOutline, DeleteOutline } from "antd-mobile-icons";
import axios from 'axios'
function Index() {
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const { PersonList } = useSelector((state) => state.PersonSlice);

  const [visible, setVisible] = useState(false);
  const [form] = Form.useForm();
  const [dialogState, setDialogState] = useState(true);
  const [EditId, setEditId] = useState(null);


  const handelAdd = () => {
    setVisible(true);
    setDialogState(true);
    form.resetFields();
  };


  const handelUpFile = () => {
    const input = document.createElement("input");
    input.type = "file";
    input.click();

    input.onchange = async () => {
      const file = input.files[0];
      const fileData = new FormData();
      fileData.append("file", file);
      const res = await axios.post("/api/orc/upload/image", fileData);
      const { code, message, data } = res.data;
      if (code === 200) {
        Toast.show({
          icon: "success",
          content: message,
        });

        form.setFieldsValue(data);
      } else {
        Toast.show({
          icon: "error",
          content: "上传失败，选择正确格式",
        });
      }
    };
  };

  const handelEidt = (item) => {
    setDialogState(false);
    form.setFieldsValue(item);
    setEditId(item.id);
  };

  const handelOk = (action) => {
    if (action.key === "confirm") {
      if (!form.getFieldValue().name || !form.getFieldValue().code) {
        Toast.show({
          icon: "error",
          content: "姓名和身份证不能为空",
        });
        return;
      }

      if (dialogState) {
        const addObj = {
          id: Number(Math.random().toString().slice(2, 6)),
          state: false,
          ...form.getFieldsValue(),
        };
        dispatch(addPer(addObj));
      } else {
        const editObj = {
          id: EditId,
          ...form.getFieldsValue(),
        };
        dispatch(EditPer(editObj));
      }
    } else {
      setVisible(false);
    }
  };
  return (
    <div>
      <NavBar onBack={() => navigate(-1)}>选择常旅客</NavBar>
      <NoticeBar
        content="不满6岁儿童可申报免费乘车，申报免费儿童票流程"
        color="alert"
      />
      <div>
        <Button
          block
          size="small"
          shape="rectangular"
          color="primary"
          onClick={() => handelAdd()}
        >
          点击按钮添加新的乘车人
        </Button>
        <Card title="乘车人列表：">
          <List>
            {PersonList.map((item, ind) => (
              <List.Item
                key={ind}
                prefix={<EditSOutline onClick={() => handelEidt(item)} />}
                extra={
                  <div>
                    <DeleteOutline
                      color="red"
                      fontSize={20}
                      style={{ marginRight: 10 }}
                      onClick={() => {
                        if (confirm("确定要删除此人乘车信息吗？")) {
                          dispatch(delPer(item));
                        }
                      }}
                    />
                    <Checkbox
                      checked={item.state}
                      onChange={() => dispatch(SwitchState(item))}
                    />
                  </div>
                }
                description={<span>{item.code}</span>}
              >
                {item.name}
              </List.Item>
            ))}
          </List>
        </Card>
      </div>

      <Modal
        visible={visible}
        content={
          <div>
            {dialogState ? (
              <Button
                block
                size="small"
                shape="rectangular"
                color="primary"
                onClick={() => handelUpFile()}
              >
                照片录入信息
              </Button>
            ) : (
              ""
            )}
            <Form layout="horizontal" form={form}>
              <Form.Header>
                {dialogState ? "添加乘车人" : "修改乘车人"}
              </Form.Header>
              <Form.Item
                name="name"
                label="姓名"
                rules={[{ required: true, message: "姓名不能为空" }]}
              >
                <Input placeholder="请输入姓名" />
              </Form.Item>
              <Form.Item
                name="code"
                label="身份证"
                rules={[{ required: true, message: "身份证不能为空" }]}
              >
                <Input placeholder="请输入身份证号" />
              </Form.Item>
            </Form>
          </div>
        }
        closeOnAction
        onClose={() => {
          setVisible(false);
        }}
        onAction={(action) => handelOk(action)}
        actions={[
          {
            key: "confirm",
            text: "确定",
          },
          {
            key: "cancel",
            text: "取消",
          },
        ]}
      ></Modal>
    </div>
  );
}

export default Index;
